package com.nothing.service.run;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.LinkedBlockingQueue;

import javax.imageio.ImageIO;

import com.nothing.domain.UserFaceImg;
import com.nothing.service.UserFaceImgService;
import com.nothing.util.ExcutorUtil;
/**
 * 
 * @author shíQíang㊚
 *
 */
public class SaveFaceImg implements Runnable {

	private LinkedBlockingQueue<BufferedImage> queue;// 阻塞队列 
	private UserFaceImgService userFaceImgService;
	 
	public SaveFaceImg(LinkedBlockingQueue<BufferedImage> queue,UserFaceImgService userFaceImgService) {
		this.queue = queue;
		this.userFaceImgService = userFaceImgService;
	}

	@Override
	public void run() {
		try {
			while (ExcutorUtil.toCheck) {
				BufferedImage data = queue.take();//.poll(2, TimeUnit.SECONDS);// 有数据时直接从队列的队首取走，无数据时阻塞，在2s内有数据，取走，超过2s还没数据，返回失败
				if (null != data) {
					try(ByteArrayOutputStream out = new ByteArrayOutputStream();){
						ImageIO.write(data, "png", out); 
						userFaceImgService.insert(UserFaceImg.builder()
								.width(data.getWidth())
								.hight(data.getHeight())
								.img(out.toByteArray())
								.state(0)
								.build());
					} catch (Exception e){} 
					data.flush();
					System.out.println("保存人脸图片");
				} else {
					System.out.println("暂无人脸图片...");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}